'use strict';

const assert = require('assert');
const ws = require('nodejs-websocket');
const path = require('path');
const Service = require('ee-core').Service;
const HOST = '127.0.0.1';
const PORT = 10011;

class WebSocketService extends Service {
  constructor(ctx) {
    super(ctx);
    this.service = null;
    this.connection = null;
  }

  /**
   * 打开websocket
   * **/
  start() {
    // 创建ws服务
    this.service = ws.createServer((conn) => {
      this.connection = conn;
      conn.on('text', (message) => {
        console.log('from client message:', message);
      });

      // 关闭
      conn.on('close', function (code, reason) {
        console.log('Connection closed');
      });

      // 报错
      conn.on('error', function (err) {
        console.log('handle err');
        console.log(err);
      });
    });

    this.service.listen(PORT, HOST, () => {
      console.log(`the websocket was successfully created on ${PORT}`);
    });
  }

  // 关闭websocket
  end() {
    this.service.close();
    this.connection = null;
  }

  /**
   * @desc Send text message through websocket service
   */
  wsConnSendText(text) {
    this.connection.sendText(text);
  }
}

WebSocketService.toString = () => '[class WebSocketService]';
module.exports = WebSocketService;
